import React from "react";
import { createMemoryHistory } from "history";
import dva from "dva";
import { StaticRouter } from "react-router-dom";
import ReactDOMServer from "react-dom/server";
import uuid from "uuid/v1";
import Loadable from 'react-loadable';
import { getBundles } from 'react-loadable/webpack';
import Test from "./pages/content/modal";
import template from "./template";
import Routes from './routes';

function generateBundleScripts( bundles = [], isCss = false ){
    return bundles.filter(bundle => bundle.file.endsWith(isCss ? '.css' : '.js')).map(bundle => {
        if(isCss){
            return `<link rel="preload" type="text/css" src="${bundle.publicPath}" />`
        }
        return `<script type="text/javascript" src="${bundle.publicPath}"></script>\n`
    });
}

export default function render(req, res) {
    const pageState = {};
    pageState[Test.namespace] = Test.state;

    const app = dva({
        history: createMemoryHistory(),
        initialState: pageState
    });

    app.model(Object.assign({}, Test));

    delete req.session.state;

    req.session.state = pageState;
    req.session.uuid = uuid();

    let modules = [];
    const render = (
        <Loadable.Capture report={moduleName => {
            modules.push(moduleName);
        }}>
            <StaticRouter location={req.url} context={{}}>
                <Routes history={createMemoryHistory()} />
            </StaticRouter >
        </Loadable.Capture>
    );

    app.router(() => {
        return render;
    });

    let html = ReactDOMServer.renderToString(app.start()());
    let bundles = getBundles(req.__stats, modules);
    // console.log(bundles);
    // console.log(2, modules);
    // console.log(1, html);
    // console.log('=================');
    delete req.__stats;
    res.send(
        template({
            body: html,
            state: req.session.uuid,
            scripts: generateBundleScripts(bundles),
            css: generateBundleScripts(bundles, true)
        })
    );
}